package de.hub.sar.itsec.sslfetcher.utils;


import java.io.*;
import de.hub.sar.itsec.sslfetcher.hosts.*;
import de.hub.sar.itsec.sslfetcher.fetcher.*;
import de.hub.sar.itsec.sslfetcher.saver.*;
import de.hub.sar.itsec.sslfetcher.log.Logger;
import de.hub.sar.itsec.sslfetcher.utils.*;
import java.util.*;

public final class FetchThread extends Thread{

	private static final String HOME_PATH = System.getProperty("user.home");
	private static final String DEFAULT_FOLDER = File.separator + "certfetcher";

	public IHostsProvider hosts;
	
	public ExampleHostProvider mk;

	public FetchThread( IHostsProvider ehp){
		 hosts = ehp;
	}

	public FetchThread( ArrayList<ContentType> data){
		 mk = new ExampleHostProvider(data);
	}

 public void run() {
	IFetcher fetcher;
	ISaver saver;
	System.out.println("I am running");
	saver = new CertSaver(HOME_PATH + DEFAULT_FOLDER, ".cert");
	fetcher = new SSLFetcher();
	ArrayList<ContentType> a = new ArrayList<ContentType>();
	a.add(new ContentType("173.194.69.94","google.de","443"));
	hosts = new ExampleHostProvider(a); //sobald das hier auskommentiert ist scheitert der Socketaufbau ?? Wieso
			for (Host host : hosts) {
				System.out.println("Test");
				fetchAndSave(fetcher, saver, host);
	}      
	System.out.println("Test3");
    }
  

	private static void fetchAndSave(final IFetcher fetcher, 
			final ISaver saver, final Host host) {
		List<byte[]> certs;
		
		try {
			System.out.println("Test2:" +host.getHost()+" "+ host.getDomain()+" "+ host.getPort());
			certs = fetcher.getCerts(host.getHost(), host.getDomain(), host.getPort());
		} catch (FetchFailsException e) {
			Logger.getInstance().error("FAILED: " + host.getHost() + " - " + host.getDomain());
			return;
		}
		
		int i = 0;
		for (byte[] cert : certs) {
			saver.save(Converter.hostToFolderName(host.getDomain()) + "-" + i++, cert);
			Logger.getInstance().info("DONE: " + host.getHost() + " - " + host.getDomain());
		}
	}
	

  }
